import 'package:decimal/decimal.dart';
import 'package:sinosheets/network/api.dart';
import 'package:sinosheets/utils/storage/LSUtil.dart';
import 'package:sinosheets/network/core/base_response.dart';

class CurrencyUtil {
  ///接口获取币种列表
  static Future<List> getCurrencyList() async {
    List currencyList = [];
    BaseResponse baseResponse = await PayApis.currentList();
    if (baseResponse.isSuccess) {
      currencyList = baseResponse.data ?? [];
    }
    return currencyList;
  }

  /// 获取对应币种金额 后台返回的都是人民币 amount 人民币
  static String rmbToCurrencyAmount(
    dynamic amount, {
    bool withSymbol = true,
    //不加小数点
    bool noDecimal = false,
  }) {
    String temp = "";
    double rate = getRate();
    String symbol = getCurrency();
    if (withSymbol) {
      temp = symbol;
    }

    /// 空值返回0
    String amountString = getPrecisionString(amount);
    if (amountString.isEmpty) {
      /// 韩元只保留整数
      if (isKorean() || noDecimal) {
        return '0 ${temp}';
      } else {
        return '0.00 ${temp}';
      }
    }

    /// 转double
    Decimal amountDecimal = Decimal.parse(amountString);
    String rateString = getPrecisionString(rate);
    Decimal rateDecimal = Decimal.parse(rateString);

    /// Decimal的除法操作异常，暂时转double
    double amountDouble = amountDecimal.toDouble();
    double rateDouble = rateDecimal.toDouble();
    double resultDouble = amountDouble / rateDouble;

    /// 韩元只保留整数
    if (isKorean() || noDecimal) {
      return '${resultDouble.toStringAsFixed(0)} $temp';
    } else {
      return '${resultDouble.toStringAsFixed(2)} $temp';
    }
  }

  /// 得到数字对应的精度字符串；异常情况返回空字符串''
  static String getPrecisionString(
    dynamic value, {
    int precision = 2,
  }) {
    if (value == null) {
      return '';
    }

    /// 拼接字符串
    String rawString = '$value';

    /// 转Decimal过渡
    Decimal? tempDecimal = Decimal.tryParse(rawString);
    if (tempDecimal == null) {
      return '';
    }

    /// 按照round方式处理精度
    return tempDecimal.round(scale: precision).toString();
  }

  /// 从本地存储读取对象
  static Map getObject() {
    Map temp = LSUtil.getCurrency();
    if (temp.isEmpty) {
      temp = {
        "currency": "CNY",
        "rate": 1.00,
        "symbol": "CNY",
      };
    }
    return temp;
  }

  /// 对象存到本地
  static saveObject(Map object) {
    LSUtil.saveCurrency(object);
  }

  /// currency字段
  static String getCurrency() {
    Map temp = getObject();
    String currency = temp["currency"] ?? "CNY";
    return currency;
  }

  /// symbol字段
  static String getSymbol() {
    Map temp = getObject();
    String symbol = temp["symbol"] ?? "CNY";
    return symbol;
  }

  /// rate字段
  static double getRate() {
    Map temp = getObject();
    double rate = temp["rate"] ?? 1.0;
    return rate;
  }

  /// 判断是不是韩元
  /// 韩元只返回整数
  static bool isKorean() {
    var currency = getCurrency();
    if (currency == 'KRW') {
      return true;
    }
    return false;
  }
}
